<?php
/**
 * FastApp.
 * 3/21/25
 * @Author deepsea
 * @Contact (telegram:deepsea159)
 */

namespace App\Hoenix\Job;

use App\Hoenix\Model\HoenixConcubine;
use App\Hoenix\Model\HoenixConcubineKeyword;
use App\Hoenix\Model\HoenixKeyword;
use Hyperf\AsyncQueue\Job;


class ConcubineKeywordJob extends Job
{

    public function __construct(public int $id, public bool $is_uid = false)
    {
    }


    public function handle(): void
    {
        try {
            if ($this->is_uid) $map = ['user_id' => $this->id]; else $map = ['id' => $this->id];
            $md = HoenixConcubine::query()->where($map)->first();
            if (!$md) return;
            $cmd = 'python3 ' . dirname(BASE_PATH) . '/py/cut.py ';
            exec($cmd . implode(',', [
                $md->reason,
                $md->self_intro,
                $md->hope,
                $md->service,
            ]), $output);
            if (empty($output)) return;
            $filtered_words = json_decode($output[0],true);
            $in = [];
            $exist = HoenixKeyword::query()->whereIn('kw', $filtered_words)->pluck('kw')->toArray();
            foreach (array_diff($filtered_words, $exist) as $word) $in[] = ['kw' => $word];
            if ($in) HoenixKeyword::query()->insert($in);
            $in = [];
            foreach (HoenixKeyword::query()->whereIn('kw', $filtered_words)->pluck('id')->toArray() as $kid)
                $in[] = ['concubine_id' => $md->id, 'kid' => $kid];
            HoenixConcubineKeyword::query()->where(['concubine_id' => $md->id])->delete();
            HoenixConcubineKeyword::query()->insert($in);
        } catch (\Throwable $throwable) {
            sys_notify($throwable->getMessage() . $throwable->getTraceAsString());
        }
    }

}